package ch.ethz.inf.shop.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.swing.JOptionPane;

import org.apache.log4j.Logger;

import com.mysql.jdbc.Driver;

/**
 * A Wrapper around an SQL Connection
 */
public final class MySQLConnection {
	private static final Logger LOGGER = Logger.getLogger(MySQLConnection.class);

	/*
	 * The connection parameters. You should change these to point to your
	 * installation specific values.
	 */
	public static final String USERNAME = "root";
	public static final String PASSWORD = "root";
	public static final String HOSTNAME = "localhost";
	public static final int PORT = 3306;
	public static final String DATABASE = "shop";

	private final Connection connection;

	/**
	 * Singleton instance: We want to avoid re-establising connections across
	 * web server requests.
	 */
	private final static MySQLConnection instance = new MySQLConnection();

	public final static MySQLConnection getInstance() {
		return MySQLConnection.instance;
	}

	private MySQLConnection() {

		Connection connection = null;

		try {
			new Driver();
			connection = DriverManager.getConnection("jdbc:mysql://" + HOSTNAME + ":" + PORT + "/" + DATABASE, USERNAME, PASSWORD);

		} catch (final SQLException e) {

			/**
			 * Make sure that we really see this error.
			 */
			System.err.println("Could not connect to MYSQL. Is the server running?");
			JOptionPane.showMessageDialog(null, "Could not connect to MYSQL. Is the server running?\n" + "Error in " + this.getClass().getName() + ".",
					"Critical Error!", JOptionPane.ERROR_MESSAGE);
			LOGGER.error("", e);

		}

		this.connection = connection;

	}

	public final Connection getConnection() {
		return this.connection;
	}

}
